<?php

function google_auth($username, $password) {	
	$username .= "@gwmail.gwu.edu";
	$url = 'https://www.google.com/accounts/ClientLogin';
	$vars = 'accountType=Hosted&Email='.$username.'&Passwd='.stripslashes($password).'&service=xapi&source=ITVET-moodle-1.8';
	
	$getauth = curl_init();
	curl_setopt($getauth,CURLOPT_URL,$url);
	curl_setopt($getauth,CURLOPT_RETURNTRANSFER,1);  
	curl_setopt($getauth,CURLOPT_POST,1);
	curl_setopt($getauth,CURLOPT_POSTFIELDS,$vars);
	$response = curl_exec($getauth);
	curl_close($getauth);
	
	if (strpos($response,'Error=CaptchaRequired')){	
		echo 'Vist <a href=https://www.google.com/accounts/DisplayUnlockCaptcha>https://www.google.com/accounts/DisplayUnlockCaptcha</a> to unlock your google account. Then re-attempt to login to our site.';
		exit();
	}
	
	if (strpos($response,'Auth=')){	
		return true;
	} 
	return false;
}

function make_pass($password) {
	return md5($password . $_GLOBALS['salt']);
}

function email_to_id($username) {
	$user = mysql_select("users",array("email"=>$username));
	if (mysql_num_rows($user)==1)	return mysql_result($user,0,"id");
	else return add_user($username);
}

function add_user($username) {
	return mysql_insert("users", array("email"=>$username));
}

function update_pass($userID, $password) {
	return mysql_update("users",array("password"=>$password),array("id"=>$userID));
}

function match_pass($userID, $password) {
	$sql = "SELECT * FROM `users` WHERE `id` = '$userID'";
	$result = mysql_query($sql);
	if (mysql_num_rows($result)==0) return false;	
	$pass = mysql_result($result,0,"password");
	if ($password == $pass) return true;
	return false;
}

function start_my_session($userID,$password) {
	$_SESSION['UserID'] = $userID;
	$_SESSION['Password'] = make_pass($password);
	update_pass($userID, make_pass($password));
}

function login($username, $password) {
	if (google_auth($username, $password)) {
		$userID = email_to_id($username);
		start_my_session($userID,$password);
		return true;
	} 
	return false;
}

function current_page() {
	return substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],"/")+1);
}

if (!function_exists('is_admin')) {
	function is_admin($id) {
		$user = get_user($id);
		return $user['admin'];
	}
}
function is_logged_in() {
	if (!is_null($_SESSION['UserID']) && !is_null($_SESSION['Password'])) return true;
	return false;
}
?>